<template>
    <el-container style="height: 100%">
        <el-main>
            <el-form
                    ref="form"
                    :inline-message="false"
                    :rules="rules"
                    :status-icon="true"
                    :model="formData"
                    label-width="120px"
                    size="large"
                    :hide-required-asterisk="true"
                    class="ser-form ope-form"
                    :v-loading="loading"
            >
                <div class="editor">
                    <div class="all-editor" v-if="allEdit===2"></div>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="资源名称：" prop="resourceName">
                                <el-input placeholder="请输入资源名称" v-model.trim="formData.resourceName"
                                         :disabled="allEdit==1" v-filterSpecialChar></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <div class="warn-info ml-30">4-16个字符，支持汉字、字母、数字、下划线、中划线
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="文件协议类型：" prop="typeId">
                                <el-select v-model="formData.typeId" :disabled="allEdit==1">
                                    <el-option
                                            v-for="item in $code.getByType('filetype')"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="IP地址：" prop="ip">
                                <el-input placeholder="请输入IP" v-model.trim="formData.ip" v-filterSpecialChar></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <div class="warn-info ml-30"></div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="端口：" prop="port">
                                <el-input placeholder="请输入端口" v-model.trim="formData.port"
                                          v-filterSpecialChar></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <div class="warn-info ml-30"></div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="路径：" prop="fileDir">
                                <el-input placeholder="请输入路径" v-model.trim="formData.fileDir"
                                          v-filterSpecialChar></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <div class="warn-info ml-30"></div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="用户名：" prop="username">
                                <el-input placeholder="请输入用户名" v-model.trim="formData.username"
                                          v-filterSpecialChar></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <div class="warn-info ml-30">1-100个字符，特殊字符支持`~!@#$%^&*()-_=+\|[{}];:'",<.>/?</div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="用户密码：" prop="password">
                                <el-input placeholder="请输入用户密码"
                                          v-filterSpecialChar
                                          v-model.trim="formData.password"
                                          type="password"
                                          onpaste="return false"
                                          onselectstart="return false"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <div class="warn-info ml-30">1-100个字符，特殊字符支持`~!@#$%^&*()-_=+\|[{}];:'",<.>/?</div>
                        </el-col>
                    </el-row>
                    <el-row v-if="formData.typeId=='1'">
                        <el-col>
                            <el-form-item label="主被动模式：" prop="activeAndPassiveMode">
                                <el-radio v-model="formData.activeAndPassiveMode"
                                          v-for="item in $code.getByType('mode')"
                                          :key="item.value"
                                          :label="item.value">{{item.label}}
                                </el-radio>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="编码：" prop="unicodeId">
                                <el-select v-model="formData.unicodeId">
                                    <el-option
                                            v-for="item in $code.getByType('unicode')"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="联系人:" prop="manager">
                                <el-input
                                        placeholder="请输入联系人"
                                        v-model="formData.manager "
                                        v-filterSpecialChar
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                          <div class=" mark ml-30">
                                2-20个字符，支持汉字
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="联系方式:" prop="phone">
                                <el-input
                                        placeholder="请输入联系方式"
                                        v-model="formData.phone "
                                        v-filterSpecialChar
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">

                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="备注：" label-width="120px" class="remark" prop="remark">
                                <el-input v-model="formData.remark" type="textarea"  placeholder="请输入备注"
                                           maxlength="200"  show-word-limit/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <div class=" mark ml-30">
                                1-200个字符，支持汉字、字母、数字、下划线
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button size="medium" @click="onBack()">取消</el-button>
                            <!--<el-button size="medium" type="primary" @click="testConnection()" :loading="saveLoading"-->
                                       <!--v-if="params.type!='add'" :disabled="allEdit === 2">-->
                                <!--测试连接-->
                            <!--</el-button>-->
                            <el-button size="medium" type="primary" @click="onSave()" :loading="saveLoading" :disabled="allEdit === 2">
                                保存
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div style="margin-top: 60px"></div>
            </el-form>
        </el-main>

    </el-container>
</template>
<script>
import { IP, isPhone, Port, validResourceName, validSpecial, validContact, validChinaSpecial, validresgeneralmid, validresMask, validdataContact } from '@/util/customRules'
import encrypt from '@/util/encrypt';

export default {
  name: 'ftpconfig',
  data() {
    return {
      rules: {
        resourceName: [
          { required: true, message: '请输入资源名称', trigger: 'blur' },
          {
            validator: ((rule, value, callback) => {
              let me = this;
              validresgeneralmid(rule, value, 4, 16, function(error) {
                if (error) {
                  callback(error);
                } else {
                  me.$api.resourcemanage.validResuseName({
                    resourceName: value,
                    resourceId: me.params.resourceId
                  }).then(res => {
                    if (res.data.code === 200) {
                      callback();
                    } else {
                      callback(new Error('资源名称已经存在!'));
                    }
                  }).catch(err => {
                    console.log(err);
                    callback(new Error('资源名称已经存在!'));
                  });
                }
              })
            }),
            trigger: 'blur'
          }
        ],
        typeId: [{ required: true, message: '请输入选择', trigger: 'change' }],
        phone: [{
          validator: ((rule, value, callback) => {
            isPhone(rule, value, callback)
          }),
          trigger: 'blur'
        }],
        ip: [
          { required: true, message: '请输入IP地址', trigger: 'blur' },
          {
            validator: ((rule, value, callback) => {
              IP(rule, value, callback)
            }),
            trigger: 'blur'
          }
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' },
          {
            validator: ((rule, value, callback) => {
              Port(rule, value, callback)
            }),
            trigger: 'blur'
          }
        ],
        fileDir: [{ required: true, message: '请输入路径', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            validator: ((rule, value, callback) => {
              let me =this;
              if (value === '') {
                callback();
              } else if (value.length >= 1 && value.length <= 100) {
                validSpecial(rule, value, function(error) {
                  if (error) {
                    callback(error);
                  } else {
                    callback();
                  }
                })
              } else {
                callback(new Error('请输入1-100个字符'));
              }

            }),
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            validator: ((rule, value, callback) => {
              if (value === '') {
                callback();
              } else if (value.length >= 1 && value.length <= 100) {
                validSpecial(rule, value, function(error) {
                  if (error) {
                    callback(error);
                  } else {
                    callback();
                  }
                })
              } else {
                callback(new Error('请输入1-100个字符'));
              }

            }),
            trigger: 'blur'
          }
        ],
        remark: [{
          validator: validresMask,
          trigger: 'blur'
        }],
        manager: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback();
              } else {
                validContact(rule, value, callback)
              }
            },
            trigger: 'blur',
          },
        ]
      },
      formData: {
        resourceName: '',
        ip: '',
        fileDir: '/',
        typeId: '',
        port: '',
        username: '',
        password: '',
        activeAndPassiveMode: 'passive',
        phone: '',
        manager: '',
        remark: '',
        unicodeId: '01'
      },
      allEdit: 0,
      saveLoading: false,
      // testValid: false,
      loading: false
    }
  },
  props: {
    params: {
      type: Object,
      default: {}
    }
  },
  methods: {
    // 返回
    onBack() {
      this.$confirm(
        (this.params.type == 'add' ? '新建' : '修改') +
        '操作尚未保存，是否确认退出？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$emit('changeComponent', {
          active: 'ftpresource'
        }
        )
      });
    },
    // 测试连接
    async testConnection(call) {
      return this.$api.resourcemanage.testConnection.call(this, Object.assign({}, this.formData, { password: encrypt.encrypt(this.formData.password) })).then(result => {
        if (result.data.code === 200) {
          this.$message({
            message: result.data.msg,
            type: 'success'
          });
          // this.testValid = true;
          return true;
        } else {
          this.$message({
            message: result.data.msg,
            type: 'error'
          });
          this.saveLoading = false;
          return false;
        }
      }).catch(() => {
        this.saveLoading = false;
        return false;
      })
    },
    save() {
      if (this.params.type === 'add') {
        // 新建时提交的数据
        this.$api.resourcemanage.fileAdd.call(this, Object.assign({}, this.formData, { password: encrypt.encrypt(this.formData.password) })).then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            this.$emit('changeComponent', {
              active: 'ftpresource'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
          this.saveLoading = false;
        }).catch(e => {
          this.saveLoading = false;
        })
      } else {
        // 修改时提交的数据
        this.$api.resourcemanage.fileModify.call(this, Object.assign({}, {
          ...this.formData,
          resourceId: this.params.resourceId
        }, { password: encrypt.encrypt(this.formData.password) })).then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            this.$emit('changeComponent', {
              active: 'ftpresource'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
          this.saveLoading = false;
        }).catch(e => {
          this.saveLoading = false;
        });
      }
    },
    // 保存
    onSave() {

      this.$refs['form'].validate((valid) => {
        if (valid) {
          // if (!this.testValid) {
          this.$confirm(
            '保存之前必须测试连接，连接成功方可保存！是否继续？',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            this.$refs['form'].validate(async(valid) => {
              if (valid) {
                this.saveLoading = true;
                let test = await this.testConnection();
                if (test) {
                  this.save();
                }
              }
            });

          });
          // } else {
          //   this.save();
          // }
        }
      })
    },
    loadData() {
      if (this.params.resourceId) {
        this.loading = true;
        this.$api.resourcemanage.getById(this.params.resourceId).then(res => {
          const result = res.data;
          if (result.code === 200) {
            let data = result.data;
            for (let key in data) {
              if (this.formData.hasOwnProperty(key)) {
                if (key == 'password') {
                  this.formData[key] = encrypt.decrypt(data[key]);
                } else {
                  this.formData[key] = data[key];
                }
                // this.formData[key] = data[key];
              }
            }
            if (data['fileTaskVoList'].length!==0) {
              let valid = true;
              data['fileTaskVoList'].forEach((d) => {
                if (d.fileTaskStatus != 0) {
                  valid = false;
                }
              });
              if (valid) {
                this.allEdit = 1;
              } else {
                this.allEdit = 2;
              }
            }
          }
          this.loading = false;

        }).catch((e) => {
          this.loading = false;
        })
      }
    }
  },

  mounted() {
    this.$nextTick(function() {
      this.loadData();
    })
  },
  beforeDestroy() {
    this.$refs.form.resetFields();
  }
}
</script>
<style lang="less" scoped>
    .remarkBox {
        // height: 80px;
    }

    .textareaInput {
        // height: 80px;
        padding: 5px;
    }

    .editor {
        position: relative;
    }

    .all-editor {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 99;
    }
</style>
